var Q = require('q'),
    entityCollection = require('../../../Base/server/controllers/EntityCollection'),
    userController = require('../../../User/server/controllers/users.server.controller'),
    BarcodeEnum = require('../../../Barcode/server/controllers/Enum.server.controller'),
    QCEnum = require('../../../QC/server/controllers/Enum.server.controller');
operationController = require('../../../CBO/server/controllers/Operation.server.controller');

//对包装货号新增条码主档
exports.insertPackageBarcode = function(packageBarcode, completeFun) {
    var entity = entityCollection.getEntity("BarcodeMaster");
    var insertData = {
        Barcode: packageBarcode,
        BarcodeType: 6,
        IsAssembly: false
    }
    entity.insert(insertData, function(err, Record) {
        completeFun(err, Record);
    });
};

//更新每个芯片条码主档
exports.updateBarcodes = function(barcodeMasters, completeFun) {
    var entity = entityCollection.getEntity("BarcodeMaster");
    var updateDatas = [];
    for (var i = 0; i < barcodes.length; i++) {
        updateDatas.push({
            Barcode: barcodeMasters[i].Barcode,
            IsAssembly: true,
            IsComplete: true
        });
    };

    entity.saves(updateDatas, function(err, record) {
        completeFun(err, record);
    });
};

//通过设备id，获取工位，作业信息,设备信息
//1，通过终端id到工位终端表中查找工位
//2，通过工位id到作业工位表中查找作业

exports.findLocationAndWork = function(deviceid, completeFun) {
    var locationName = ''; //工位name
    var locationId = ''; //工位Id
    var workName = ''; //作业name
    var workId = ''; //作业Id
    var deviceId = ''; //设备id
    var deviceName = ''; //设备name
    var record = {};

    findTerminal_ID(deviceid).then(function(result1) {
        deviceId = result1._id;
        deviceName = result1.Name;
        findStationTerminal(deviceId).then(function(result2) {
            locationName = result2.WorkLocation.Name;
            locationId = result2.WorkLocation._id;
            findStationWork(locationId).then(function(result3) {
                workName = result3.Work.Name;
                workId = result3.Work._id;
                record = {
                    locationName: locationName,
                    locationId: locationId,
                    workName: workName,
                    workId: workId,
                    deviceId: deviceId,
                    deviceName: deviceName
                };
                completeFun(null, record);

            }, function(err) {
                completeFun(err, record);
                alert("未找到该作业");
            });
        }, function(err) {
            alert("未找到该工位");
        });
    }, function(err) {
        alert("未找到该设备id");
    });
};


//增加条码装配关系记录
//1,查找包装货号的条码主档id

//3,增加条码装配关系AssemblyRelation
exports.insertPackageAssemblyRelation = function(packageBarcode, barcodeMasters, completeFun) {
    var packageBarcodeId = '';

    findPackageBarcodeID(packageBarcode).then(function(result1) {
        packageBarcodeId = result1._id;
        var entity = entityCollection.getEntity("AssemblyRelation");
        var addDatas = [];
        var dateNow = Date.now();
        for (var i = 0; i < barcodeMasters.length; i++) {
            addDatas.push({
                BarcodeMaster: packageBarcodeId,
                AssemblyBarcode: barcodeMasters[i]._id,
                AssemblyType: 1,
                CollectDateTime: dateNow
            });
        };

        entity.saves(addDatas, function(err, record) {
            completeFun(err, record);
        });

    }, function(err) {
        alert("未找到该包装货号");
    });
};

//增加入库记录数据
exports.insertStockingRecord = function(barcodeMasters, userId, operationId, BizRecordIds, completeFun) {
    var entity = entityCollection.getEntity("RcvRecord");
    var addDatas = [];
    var dateNow = Date.now();
    for (var i = 0; i < barcodeMasters.length; i++) {
        addDatas.push({
            BarcodeMaster: barcodeMasters[i]._id,
            Barcode: barcodeMasters[i].Barcode,
            RcvBusinessType: 0,
            BusinessDocID: barcodeIds[i].MO,
            ItemMaster: barcodeIds[i].ItemMaster,
            RcvUser: userId,
            RcvDateTime: dateNow,
            RcvQty: 1,
            RcvOperation: operationId,
            BizRecord: BizRecordIds[i]
        });
    };

    entity.saves(addDatas, function(err, record) {
        completeFun(err, record);
    });

};



//新增入库的物料集合的条码流水
exports.insertBarcodesFlow = function(barcodeMasters, deviceId, deviceName, workId, workName, locationId, locationName, userId, completeFun) {

    var operationName = ''; //工序
    var operationId = ''; //工序id

    var addDatas = [];

    // findItemMasterID(barcodeMasters[0].).then(function(result) {

    operationController.findByItemMasterAndWork2(barcodeMasters[0].ItemMaster, workId, function(err, record) {
        if (err) {
            alert("未找到对应工序");
        } else {
            if (record != null) {
                operationName = record.Name;
                operationId = record._id;

                var dateNow = Date.now();
                for (var i = 0; i < barcodeMasters.length; i++) {
                    addDatas.push({
                        BarcodeMaster: barcodeMasters[i]._id,
                        Terminal: deviceId,
                        TerminalName: deviceName,
                        Operation: operationId,
                        OperationName: operationName,
                        Work: workId,
                        WorkName: workName,
                        WorkLocation: locationId,
                        WorkLocationName: locationName,
                        Users: [userId],
                        CollectDateTime: dateNow,
                        BusinessStatus: 1,

                    });
                };
                entity.saves(addDatas, function(err, record) {
                    completeFun(err, record, operationId);
                });
            }
        }
    });
    // }, function(err) {
    //     alert("未找到对应物料");
    // });

};
//查找终端id
function findTerminal_ID(deviceid) {
    var deferred = Q.defer();
    var entityTerminal = entityCollection.getEntity("Terminal");
    entityTerminal.findOne({
            UniqueID: deviceid
        }, [{
            path: '_id'
        }, {
            path: 'Name'
        }],
        function(err, record) {
            if (err) {
                deferred.reject(err);
                return;
            } else {
                deferred.resolve(record)
            }
        }
    );
    return deferred.promise;
}
//查找工位
function findStationTerminal(terminalid) {
    var deferred = Q.defer();
    var entityStationTerminal = entityCollection.getEntity("StationTerminal");
    entityStationTerminal.findOne({
            Terminal: terminalid
        }, [{
            path: 'WorkLocation',
            select: '_id Name'
        }, ],
        function(err, record) {
            if (err) {
                deferred.reject(err);
                return;
            } else {
                deferred.resolve(record)
            }
        }
    );
    return deferred.promise;
}

//查找作业
function findStationWork(locationid) {
    var deferred = Q.defer();
    var entityStationWork = entityCollection.getEntity("StationWork");
    entityStationWork.findOne({
            WorkLocation: locationid
        }, [{
            path: 'Work',
            select: '_id Name'
        }, ],
        function(err, record) {
            if (err) {
                deferred.reject(err);
                return;
            } else {
                deferred.resolve(record)
            }
        }
    );
    return deferred.promise;
}
//查找条码对应的物料id
function findItemMasterID(barcode) {
    var deferred = Q.defer();
    var entity = entityCollection.getEntity("BarcodeMaster");
    entity.findOne({
            Barcode: barcode
        }, [{
            path: 'ItemMaster',
        }, {
            path: '_id',
        }],
        function(err, record) {
            if (err) {
                deferred.reject(err);
                return;
            } else {
                deferred.resolve(record)
            }
        }
    );
    return deferred.promise;
}
//查找包装货号的id
function findPackageBarcodeID(packageBarcode) {
    var deferred = Q.defer();
    var entity = entityCollection.getEntity("BarcodeMaster");
    entity.findOne({
            Barcode: packageBarcode
        }, [{
            path: '_id',
        }],
        function(err, record) {
            if (err) {
                deferred.reject(err);
                return;
            } else {
                deferred.resolve(record)
            }
        }
    );
    return deferred.promise;
}
//查找每个芯片的id
function findBarcodeID(Barcode) {
    var deferred = Q.defer();
    var entity = entityCollection.getEntity("BarcodeMaster");
    entity.findOne({
            Barcode: Barcode
        }, [{
            path: '_id',
        }],
        function(err, record) {
            if (err) {
                deferred.reject(err);
                return;
            } else {
                deferred.resolve(record)
            }
        }
    );
    return deferred.promise;
}

//根据装配条码查找其条码主档id
exports.findAssemblyBarcodeMasterId = function(barcode, completeFun) {
    var entity = entityCollection.getEntity("BarcodeMaster");
    entity.findOne({
            Barcode: barcode
        }, [{
            path: '_id'
        }, ],
        function(err, record) {
            if (err) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询条码主档错误';
                newErr.message = '查询失败，请检查查询参数！';
                completeFun(newErr);
            } else {
                completeFun(null, record);
            }
        }
    );
};
//根据装配的条码主档id到装配表中找到对应的主档
exports.findAssemblyBarcodeMaster = function(ID, completeFun) {
    var entity = entityCollection.getEntity("AssemblyRelation");
    entity.findOne({
            AssemblyBarcode: ID
        }, [{
            path: 'BarcodeMaster',
            select: '_id Barcode ItemMaster ItemMasterCode MO MOCode ShipLotNumber'
        }, ],
        function(err, record) {
            if (err) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询条码主档错误';
                newErr.message = '查询失败，请检查查询参数！';
                completeFun(newErr);
            } else {
                completeFun(null, record);
            }
        }
    );
};
//根据条码查找条码主档
exports.findBarcodeMaster = function(barcode, completeFun) {
    var entity = entityCollection.getEntity("BarcodeMaster");
    entity.findOne({ Barcode: barcode }, [
            { path: 'ItemMaster', select: 'Code Name Specification ItemCategory' },
            { path: 'MO', select: 'Code LotNumber Customer StartDateTime EndDateTime' },
            { path: 'Work', select: 'Name' },
            { path: 'BizRecord' },
            { path: 'Operation' },
            { path: 'Users', select: 'Code Name' }
        ],
        function(err, record) {
            if (err) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询条码主档错误';
                newErr.message = '查询失败，请检查查询参数！';
                completeFun(newErr);
            } else {
                completeFun(null, record);
            }
        }
    );
};

exports.findBarcodeMasterAllData = function(barcode, completeFun) {
    var entity = entityCollection.getEntity("BarcodeMaster");
    entity.findOne({ Barcode: barcode }, null,
        function(err, record) {
            if (err) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询条码主档错误';
                newErr.message = '查询失败，请检查查询参数！';
                completeFun(newErr);
            } else {
                completeFun(null, record);
            }
        });
};

//根据条码主档查找条码主档所有信息
exports.findBarcodeMasterByBarcodeMaster = function(barcodeMaster, completeFun) {
    var entity = entityCollection.getEntity("BarcodeMaster");
    entity.findOne({ _id: barcodeMaster }, null,
        function(err, record) {
            if (err) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询条码主档错误';
                newErr.message = '查询失败，请检查查询参数！';
                completeFun(newErr);
            } else {
                completeFun(null, record);
            }
        });
};

//根据条码查找条码主档
exports.findBarcodeMasters = function(barcodes, completeFun) {
    var entity = entityCollection.getEntity("BarcodeMaster");
    entity.find({ Barcode: { $in: barcodes } }, { Barcode: 1 }, [
            { path: 'Operation', select: 'WareHouse' }
        ],
        function(err, record) {
            if (err) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询条码主档错误';
                newErr.message = '查询失败，请检查查询参数！';
                completeFun(newErr);
            } else {
                completeFun(null, record);
            }
        }
    );
};

//查找不合格条码主档
exports.findBadMasters = function(completeFun) {
    var entity = entityCollection.getEntity("BarcodeMaster");
    entity.Entity
        .find({
            BarcodeType: BarcodeEnum.BarcodeType.ItemMaster,
            QCStatus: QCEnum.QCStatus.Decide
        }, { Barcode: 1, WorkName: 1, WorkLocationName: 1, Users: 1, MOLotNumber: 1, ItemMasterCode: 1, ItemMasterName: 1 })
        .populate({ path: 'Users', select: 'Code Name' })
        .exec(function(err, records) {
            if (err) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询条码主档错误';
                newErr.message = '查询失败，请检查查询参数！';
                completeFun(newErr);
            } else {
                completeFun(null, records);
            }
        });
};

exports.findUser = function(barcode, completeFun) {
    var entity = entityCollection.getEntity("BarcodeMaster");
    entity.findOne({ Barcode: barcode }, null, function(err, record) {
        if (err) {
            var newErr = new Error();
            newErr.leval = 9;
            newErr.title = '查询条码主档错误';
            newErr.message = '查询失败，请检查查询参数！';
            completeFun(newErr);
        } else {
            if (record == null) {
                var newErr = new Error();
                newErr.leval = 9;
                newErr.title = '查询条码主档失败';
                newErr.message = '该条码在系统中不存在！';
                completeFun(newErr);
            } else {
                if (record.BarcodeType != BarcodeEnum.BarcodeType.Person) {
                    var newErr = new Error();
                    newErr.leval = 9;
                    newErr.title = '查询员工信息失败';
                    newErr.message = '该条码不是员工条码！';
                    completeFun(newErr);
                } else {
                    userController.getUserAndRolesInfo(record.EntityID, function(err, user) {
                        completeFun(err, user);
                    });
                }
            }
        }
    });
};

exports.updateByValue = function(barcode, value, completeFun) {
    var entity = entityCollection.getEntity("BarcodeMaster");
    entity.updateByValue({ Barcode: barcode }, value, function(err, result) {
        completeFun(err, result);
    });
};
/**
 * [findBarcodeMasterByCoditions 根据条件查询条码主档]
 * author jiadx
 * @param  MOLotNumber     [批次（可为空）]
 * @param  completeFun
 * @return {[type]}             [条码主档记录]
 */
exports.findAllBarcodeMaster = function(optNum, completeFun) {
    var entityDepartment = entityCollection.getEntity("WorkLocation");
    //查询工位和部门保存到对象，作为对照表

    entityDepartment.find({}, null, {
        path: 'Department',
        select: 'Code Name'
    }, function(err, records) {
        if (err) {
            completeFun(err);
            return;
        }
        var department = {};
        records.forEach(function(record) {
            if (!department.hasOwnProperty(record._id)) {
                department[record._id] = {
                    workLocation: record._id,
                    departmentCode: record.Department ? record.Department.Code : '',
                    department: record.Department ? record.Department.Name : ''
                };
            }
        });
        //条码主档进行分组
        var entity = entityCollection.getEntity("BarcodeMaster");
        var barcodeMap = function() {
            emit(this.MOLotNumber, { WorkLocations: [this.WorkLocation] });
        };
        var barcodeReduce = function(key, values) {
            var res = { WorkLocations: [] };
            values.forEach(function(val) {
                val.WorkLocations.forEach(function(WorkLocation) {
                    res.WorkLocations.push(WorkLocation);
                });
            });
            return res;
        };

        var barcodeQuery = {
            IsComplete: false
        };

        if (optNum) {
            barcodeQuery.MOLotNumber = { $in: optNum };
        }

        var option = {
            map: barcodeMap,
            reduce: barcodeReduce,
            sort: { MOLotNumber: -1 },
            query: barcodeQuery
        };

        entity.mapReduce(option, function(err, results) {
            if (err) {
                completeFun(err);
                return;
            }
            var lastArr = [];
            for (var i = 0; i < results.length; i++) {
                var lastResult = {
                    MoLotNum: results[i]._id
                };
                for (var j = 0; j < results[i].value.WorkLocations.length; j++) {
                    if (department.hasOwnProperty(results[i].value.WorkLocations[j])) {
                        results[i].value.WorkLocations[j] = department[results[i].value.WorkLocations[j]].department;
                    }
                    if (!lastResult.hasOwnProperty(results[i].value.WorkLocations[j])) {
                        lastResult[results[i].value.WorkLocations[j]] = 0;
                    }
                    if (lastResult.hasOwnProperty(results[i].value.WorkLocations[j])) {
                        lastResult[results[i].value.WorkLocations[j]] += 1;
                    }
                }
                lastArr.push(lastResult);
            }
            completeFun(err, lastArr);
        });
    });
};

//插入条码主档
exports.createBarcodeMaster = function(barcodeMasterData, completeFun) {
    var barcodeMasterEntity = entityCollection.getEntity("BarcodeMaster");
    barcodeMasterEntity.insert(barcodeMasterData, function(err, newBarcodeMaster) {
        completeFun(err, newBarcodeMaster);
    });
};

//删除条码主档
exports.deleteById = function(id, completeFun) {
    var barcodeMasterEntity = entityCollection.getEntity("BarcodeMaster");
    barcodeMasterEntity.deleteById(id, function(err, result) {
        completeFun(err, result);
    });
};
